package lunchy.mvc.views;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Shell;

import lunchy.main.CLunchyApplication;
import lunchy.mvc.controllers.CLunchyLoginDialogController;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Button;

public class CLunchyLoginDialogView
{
	private Shell shellLogin;
	private CLunchyLoginDialogController controller;
	private Text loginText;
	private Text passwordText;
	
	public CLunchyLoginDialogView()
	{
		controller = new CLunchyLoginDialogController();
		
		shellLogin = new Shell(CLunchyApplication.getInstance().display, SWT.CLOSE | SWT.TITLE | SWT.MIN | SWT.APPLICATION_MODAL);
		shellLogin.setMinimumSize(new Point(200, 100));
		shellLogin.setText("LunchY | Login");
		shellLogin.setSize(259, 135);
		
		initUI();
		
		shellLogin.open();
        
        while (!shellLogin.isDisposed())
        {
        	if (!CLunchyApplication.getInstance().display.readAndDispatch())
        		CLunchyApplication.getInstance().display.sleep();
        }
	}
	
	private void initUI()
	{
		Label loginLabel = new Label(shellLogin, SWT.NONE);
		loginLabel.setBounds(10, 24, 59, 14);
		loginLabel.setText("Логин");
		
		Label passwordLabel = new Label(shellLogin, SWT.NONE);
		passwordLabel.setBounds(10, 44, 59, 14);
		passwordLabel.setText("Пароль");
		
		loginText = new Text(shellLogin, SWT.BORDER);
		loginText.setBounds(63, 21, 186, 19);
		
		passwordText = new Text(shellLogin, SWT.BORDER | SWT.PASSWORD);
		passwordText.setBounds(63, 44, 186, 19);
		
		Button loginButton = new Button(shellLogin, SWT.NONE);
		loginButton.setBounds(63, 69, 94, 28);
		loginButton.setText("Войти");
		loginButton.addMouseListener(
			new MouseListener()
			{
				public void mouseUp(MouseEvent e)
				{
					if(controller.tryLogin(loginText.getText(), passwordText.getText()))
					{
						shellLogin.dispose();
					}
					else
					{
						MessageBox errorMessage = new MessageBox(shellLogin, SWT.ICON_ERROR);
						errorMessage.setText("Ошибка входа!");
						errorMessage.setMessage("Не верный логин или пароль!");
						errorMessage.open();
					}
				}
				
				public void mouseDown(MouseEvent e)
				{
				}
				
				public void mouseDoubleClick(MouseEvent e)
				{
				}
			}
		);
		
		Button cancelButton = new Button(shellLogin, SWT.NONE);
		cancelButton.setText("Отмена");
		cancelButton.setBounds(155, 69, 94, 28);
		cancelButton.addMouseListener(
			new MouseListener()
			{
				public void mouseUp(MouseEvent e)
				{
					shellLogin.dispose();
				}
				
				public void mouseDown(MouseEvent e)
				{
				}
				
				public void mouseDoubleClick(MouseEvent e)
				{
				}
			}
		);
	}
}
